<template>
    <el-container>
        <el-aside width="50%">
            <avue-crud ref="multipleTable" :data="tableData" :option="tableColumns" :page="page" highlight-current-row
                @row-click="handleRowClick" @refresh-change="refresh" @search-change="searchChange" @search-reset="searchReset"
                @filter-change="filterChange" @size-change="sizeChange" @current-change="currentChange">
                <template slot="menuLeft">
                    <el-button v-for="(item,index) in btnList" :key="index" :type="item.type" :class="item.hide?'hide':''"
                        @click.native="btnclick(item.funName)" size="small">{{ item.label }}</el-button>
                </template>
                <template slot="menu" slot-scope="{row}">
                    <el-button v-if="$store.getters.userInfo.user_type === 0" size="small" type="text" class="primarybtn-color"
                        @click.native="edit(row)">
                        编辑
                    </el-button>
                    <el-button v-if="$store.getters.userInfo.user_type === 0" size="small" type="text" class="dangerbtn-color"
                        @click.native="del(row)">
                        删除
                    </el-button>
                </template>
            </avue-crud>
            <el-dialog :title="dialogFormTitle" :destroy-on-close="false" :close-on-click-modal="false" :visible.sync="dialogFormVisible"
                :before-close="handleCloseBindDialogForm" top="25vh" width="400px">
                <div style="height:20vh;overflow:auto">
                    <df-element-form v-if="formHackReset" ref="customForm" :formConfig="formConfig[0]" :value="formValue">
                    </df-element-form>
                </div>
                <el-row slot="footer" class="dialog-footer" style="text-align: center;">
                    <el-button size="small" type="primary" @click="save">保存</el-button>
                    <el-button size="small" @click="dialogFormVisible = false;">取消</el-button>
                </el-row>
            </el-dialog>
        </el-aside>
        <el-main>
            <avue-crud ref="detailTable" :data="detailtableData" :page="detailpage" :option="detailtableColumns"
                @refresh-change="detailrefresh" @size-change="detailsizeChange" @current-change="detailcurrentChange">
                <template slot="menuLeft">
                    <el-button v-for="(item,index) in detailbtnList" :key="index" :type="item.type" :class="item.hide?'hide':''"
                        @click.native="btnclick(item.funName)" size="small">{{ item.label }}</el-button>
                </template>
                <template slot="menu" slot-scope="{row}">
                    <el-button v-if="$store.state.user.permission.dict_detail_enabled && row.status === 0" size="small"
                        type="text" class="successbtn-color" @click.native="detailenabled(row)">
                        启用
                    </el-button>
                    <el-button v-if="$store.state.user.permission.dict_detail_edit" size="small" type="text" class="primarybtn-color"
                        @click.native="detailedit(row)">
                        编辑
                    </el-button>
                    <el-button v-if="$store.state.user.permission.dict_detail_del" size="small" type="text" class="dangerbtn-color"
                        @click.native="detaildel(row)">
                        删除
                    </el-button>
                    <el-button v-if="$store.state.user.permission.dict_detail_disabled && row.status === 1" size="small"
                        type="text" class="dangerbtn-color" @click.native="detaildisabled(row)">
                        禁用
                    </el-button>
                </template>
                <template slot="status" slot-scope="scope">
                    <div v-if="scope.row.status === 1" style="color:#13ce66">启用</div>
                    <div v-if="scope.row.status === 0" style="color:#ff4949">禁用</div>
                </template>
            </avue-crud>
            <el-dialog :title="detailinnerDialogFormTitle" :destroy-on-close="false" :close-on-click-modal="false"
                :visible.sync="detailinnerVisible" :before-close="handleCloseBindDetailDialogForm" append-to-body top="25vh"
                width="400px">
                <div style="height:20vh;overflow:auto">
                    <df-element-form v-if="detailFormHackReset" ref="detailForm" :formConfig="formConfig[1]" :value="detailFormValue">
                    </df-element-form>
                </div>
                <el-row slot="footer" class="dialog-footer" style="text-align: center;">
                    <el-button size="small" type="primary" @click="detailsave">保存</el-button>
                    <el-button size="small" @click="detailinnerVisible = false;">取消</el-button>
                </el-row>
            </el-dialog>
        </el-main>
    </el-container>
</template>

<script>
    import {
        api
    } from "@/api/common";
    import {
        getFormConfigData
    } from '@/const/views/system/dev/dict'
    // import { getFilesByKey } from '@/util/upload';
    import SearchCol from '@/components/view/search_col'

    export default {
        components: {
            SearchCol
        },
        data() {
            return {
                formHackReset: true,
                detailFormHackReset: true,
                editType: 'type',
                editTypeID: '',
                editDetailID: '',
                formConfig: [], // 表单配置数据
                formValue: {}, // 表单值
                dialogFormVisible: false, // 弹出框显示
                dialogFormTitle: '', // 弹出框标题
                detailFormValue: {}, // 字典明细表单值
                dialogDetailFormVisible: false, // 字典明细弹出框显示
                dialogDetailFormTitle: '', // 字典明细弹出框标题
                detailinnerVisible: false, // 字典明细内层弹出框显示
                detailinnerDialogFormTitle: '', // 字典明细内层弹出框标题
                page: {
                    currentPage: 1,
                    total: 0,
                    pageSize: 10
                }, // 分页信息
                searchForm: {}, // 搜索框记录
                filterForm: {}, // 过滤框记录
                btnList: [{
                    type: "primary",
                    funName: "add",
                    label: "添加",
                    hide: this.$store.getters.userInfo.user_type !== 0
                }],
                tableData: [], // 表格数据
                tableColumns: { // 表格列配置
                    highlightCurrentRow: true,
                    border: true,
                    stripe: false,
                    showHeader: true,
                    index: false,
                    page: true,
                    align: 'left',
                    menuAlign: 'center',
                    addBtn: false,
                    delBtn: false,
                    editBtn: false,
                    menu: true,
                    // menuWidth: '260px',
                    columnBtn: false,
                    searchMenuSpan: 8,
                    column: [{ // 表格列
                        prop: "name",
                        label: "名称"
                    }, {
                        prop: "code",
                        label: "代码",
                    }, {
                        prop: "remark",
                        label: "备注",
                    }, {
                        label: '快捷搜索',
                        prop: 'keyword',
                        search: true,
                        hide: true,
                        searchPlaceholder: '名称,代码'
                    }]
                },
                detailbtnList: [{
                    type: "primary",
                    funName: "detailadd",
                    label: "添加",
                    hide: !this.$store.state.user.permission.dict_detail_add && this.$store.getters.userInfo.user_type !==
                        0
                }, {
                    type: "primary",
                    funName: "detailenabled",
                    label: "启用",
                    hide: !this.$store.state.user.permission.dict_detail_enabled && this.$store.getters.userInfo
                        .user_type !== 0
                }, {
                    type: "danger",
                    funName: "detaildisabled",
                    label: "禁用",
                    hide: !this.$store.state.user.permission.dict_detail_disabled && this.$store.getters.userInfo
                        .user_type !== 0
                }, {
                    type: "danger",
                    funName: "detaildel",
                    label: "删除",
                    hide: !this.$store.state.user.permission.dict_detail_del && this.$store.getters.userInfo.user_type !==
                        0
                }],
                detailpage: {
                    currentPage: 1,
                    total: 0,
                    pageSize: 10
                }, // 分页信息
                detailtableData: [], // 表格数据
                detailtableColumns: { // 表格列配置
                    border: true,
                    stripe: false,
                    selection: true, // 多选
                    showHeader: true,
                    index: false,
                    page: true,
                    align: 'left',
                    menuAlign: 'center',
                    addBtn: false,
                    delBtn: false,
                    editBtn: false,
                    menu: true,
                    menuWidth: '150px',
                    columnBtn: false,
                    column: [{ // 表格列
                        prop: "name",
                        label: "名称"
                    }, {
                        prop: "status",
                        label: "状态",
                        slot: true
                    }, {
                        prop: "orders",
                        label: "排序",
                    }]
                }
            }
        },
        created() {
            this.getTableList();
            this.getFormConfig();
        },
        methods: {
            // 表格刷新
            refresh() {
                this.getTableList();
            },
            // 搜索
            searchChange(params, done) {
                this.page.currentPage = 1
                this.getTableList(params)
                Object.assign(this.searchForm, params)
                done()
            },
            // 搜索清空
            searchReset() {
                this.page.currentPage = 1
                this.$set(this.searchForm, 'keyword', '')
                this.getTableList()
            },
            // 表格过滤（高级搜索）
            filterChange(result) {
                // console.log(result)
                this.getTableList(result)
                this.filterForm = result
            },
            // 分页
            sizeChange(val) {
                this.page.currentPage = 1
                this.page.pageSize = val
                this.getTableList();
            },
            // 当前页
            currentChange(val) {
                this.page.currentPage = val
                this.getTableList();
            },
            // 绑定弹窗子组件的关闭
            handleCloseBindDialogForm() {
                this.dialogFormVisible = false
                this.dialogFormTitle = ''
            },
            // 行单击
            handleRowClick(row, event, column) {
                console.log(row, event, column)
                this.editTypeID = row.id
                this.getDetailTableList()
            },
            // 获取表格数据
            getTableList(where) {
                let params = {
                    page: this.page.currentPage,
                    limit: this.page.pageSize
                }
                params = Object.assign({}, params, this.searchForm)
                params = Object.assign({}, params, this.filterForm)
                if (where) {
                    params = Object.assign({}, params, where)
                }
                let _this = this
                _this.axios.post(api.getDictTypeList, params, ).then((res) => {
                    // console.log(res)
                    if (res.data.code == 10000) {
                        _this.tableData = res.data.data.list
                        _this.page.total = res.data.data.count
                        setTimeout(() => {
                            if (_this.$refs.multipleTable.data.length > 0) {
                                _this.$refs.multipleTable.setCurrentRow(_this.$refs.multipleTable.data[
                                    0]);
                                _this.editTypeID = _this.$refs.multipleTable.data[0].id
                                _this.getDetailTableList()
                            }
                        }, 10)
                    } else {
                        _this.tableData = []
                        _this.page.total = 0
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    _this.tableData = []
                    _this.page.total = 0
                    console.log('调用失败', err)
                })
            },
            // 字典明细表格刷新
            detailrefresh() {
                this.getDetailTableList();
            },
            // 字典明细分页
            detailsizeChange(val) {
                this.detailpage.currentPage = 1
                this.detailpage.pageSize = val
                this.getDetailTableList();
            },
            // 字典明细当前页
            detailcurrentChange(val) {
                this.detailpage.currentPage = val
                this.getDetailTableList();
            },
            // 字典明细绑定弹窗子组件的关闭
            handleCloseBindDetailDialogForm() {
                this.detailinnerVisible = false
                this.detailinnerDialogFormTitle = ''
            },
            // 字典明细获取表格数据
            getDetailTableList() {
                let params = {
                    page: this.detailpage.currentPage,
                    limit: this.detailpage.pageSize,
                    parent_id: this.editTypeID,
                }
                let _this = this
                _this.axios.post(api.getDictList, params, ).then((res) => {
                    console.log(res)
                    if (res.data.code == 10000) {
                        _this.detailtableData = res.data.data.list
                        _this.detailpage.total = res.data.data.count
                    } else {
                        _this.detailtableData = []
                        _this.detailpage.total = 0
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    _this.tabdetailtableDataleData = []
                    _this.detailpage.total = 0
                    console.log('调用失败', err)
                })
            },
            // 获取表单配置
            getFormConfig() {
                var _this = this

                _this.formConfig = getFormConfigData()
            },
            // 按钮点击（转发）
            btnclick(func) {
                this[func]()
            },
            // 字典明细添加
            detailadd() {
                if (this.editTypeID === '') {
                    this.$message({
                        showClose: false,
                        message: '请选择字典分类后进行操作！',
                        type: 'info'
                    });
                    return false;
                }

                this.editDetailID = ''
                this.editType = 'detail'
                this.$set(this.formConfig[1], 'disabled', false)
                this.detailFormValue = {}
                this.detailFormHackReset = false
                this.$nextTick(() => {
                    this.detailFormHackReset = true
                })
                this.detailinnerVisible = true
                this.detailinnerDialogFormTitle = '添加字典明细'
            },
            // 添加
            add() {
                this.editTypeID = ''
                this.editType = 'type'
                this.$set(this.formConfig[0], 'disabled', false)
                this.formValue = {}
                this.formHackReset = false
                this.$nextTick(() => {
                    this.formHackReset = true
                })
                this.dialogFormVisible = true
                this.dialogFormTitle = '添加字典类型'
            },
            // 表格行操作列按钮点击（转发）
            rowbtnclick(func, row) {
                this[func](row)
            },
            // 编辑
            async edit(row) {
                this.editTypeID = row.id
                this.editType = 'type'
                let _this = this
                _this.axios.post(api.getDictTypeById, {
                    id: row.id
                }).then((res) => {
                    console.log(res)
                    if (res.data.code == 10000) {
                        _this.$set(_this.formConfig[0], 'disabled', false)
                        _this.formValue = Object.assign({}, res.data.data)
                        _this.formHackReset = false
                        _this.$nextTick(() => {
                            _this.formHackReset = true
                        })
                        _this.dialogFormVisible = true
                        _this.dialogFormTitle = '编辑【' + row.name + '】字典类型'
                    } else {
                        _this.formValue = {}
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        })
                    }
                }).catch((err) => {
                    _this.formValue = {}
                    _this.$message({
                        showClose: false,
                        message: '获取字典类型详情失败！',
                        type: 'error'
                    })
                    console.log('调用失败', err)
                })
            },
            // 删除
            del(row) {
                let url = api.dictTypeRmv,
                    _this = this,
                    params = {
                        id: row.id,
                    }

                _this.$confirm('该操作会永久删除该字典类型[' + row.name + '], 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params)
                }).catch(() => {});
            },
            // 启用
            detailenabled(row) {
                let url = api.dictSts,
                    params = {
                        id: '',
                        status: 1
                    },
                    _this = this
                let _sucess_callback = function() {
                    _this.getDetailTableList()
                    _this.handleCloseBindDetailDialogForm()
                }

                if (row) { // 表格行操作
                    params.id = row.id
                } else { // 多行操作
                    let tableSelect = Object.assign({}, _this.$refs.detailTable.tableSelect)
                    for (var index in tableSelect) {
                        // if (tableSelect[index].status !== 0) {
                        //   this.$alert('请选择全部都是禁用的数据进行启用', '提示', {
                        //     confirmButtonText: '确定'
                        //   });
                        //   return
                        // }else{
                        params.id += ',' + tableSelect[index].id
                        // }
                    }
                    params.id = params.id.replace(/^(\s|,)+|(\s|,)+$/g, '');
                }

                if (params.id === '') {
                    _this.$message({
                        showClose: false,
                        message: '请选择需要启用的记录！',
                        type: 'info'
                    });
                    return false
                }

                _this.$confirm('是否确认启用字典?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params, _sucess_callback)
                }).catch(() => {});
            },
            // 禁用
            detaildisabled(row) {
                let url = api.dictSts,
                    params = {
                        id: '',
                        status: 0
                    },
                    _this = this

                let _sucess_callback = function() {
                    _this.getDetailTableList()
                    _this.handleCloseBindDetailDialogForm()
                }

                if (row) { // 表格行操作
                    params.id = row.id
                } else { // 多行操作
                    let tableSelect = Object.assign({}, _this.$refs.detailTable.tableSelect)
                    for (var index in tableSelect) {
                        // if (tableSelect[index].status !== 1) {
                        //   this.$alert('请选择全部都是启用的数据进行禁用', '提示', {
                        //     confirmButtonText: '确定'
                        //   });
                        //   return
                        // }else{
                        params.id += ',' + tableSelect[index].id
                        // }
                    }
                    params.id = params.id.replace(/^(\s|,)+|(\s|,)+$/g, '');
                }

                if (params.id === '') {
                    _this.$message({
                        showClose: false,
                        message: '请选择需要禁用的记录！',
                        type: 'info'
                    });
                    return false
                }

                _this.$confirm('是否确认禁用字典?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params, _sucess_callback)
                }).catch(() => {});
            },
            // 字典明细编辑
            detailedit(row) {
                this.editDetailID = row.id
                this.editType = 'detail'
                let _this = this
                _this.axios.post(api.getDictById, {
                    id: row.id
                }).then((res) => {
                    console.log(res)
                    if (res.data.code == 10000) {
                        _this.$set(_this.formConfig[1], 'disabled', false)
                        _this.detailFormValue = Object.assign({}, res.data.data)
                        _this.detailFormHackReset = false
                        _this.$nextTick(() => {
                            _this.detailFormHackReset = true
                        })
                        _this.detailinnerVisible = true
                        _this.detailinnerDialogFormTitle = '编辑【' + row.name + '】字典明细'
                    } else {
                        _this.detailFormValue = {}
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        })
                    }
                }).catch((err) => {
                    _this.detailFormValue = {}
                    _this.$message({
                        showClose: false,
                        message: '获取字典明细详情失败！',
                        type: 'error'
                    })
                    console.log('调用失败', err)
                })
            },
            // 字典明细删除
            detaildel(row) {
                let url = api.dictRmv,
                    _this = this,
                    params = {
                        id: '',
                    }

                let _sucess_callback = function() {
                    _this.getDetailTableList()
                    _this.handleCloseBindDetailDialogForm()
                }

                if (row) { // 表格行操作
                    params.id = row.id
                } else { // 多行操作
                    let tableSelect = Object.assign({}, _this.$refs.detailTable.tableSelect)
                    for (var index in tableSelect) {
                        params.id += ',' + tableSelect[index].id
                    }
                    params.id = params.id.replace(/^(\s|,)+|(\s|,)+$/g, '');
                }
                if (params.id === '') {
                    _this.$message({
                        showClose: false,
                        message: '请选择需要删除的记录！',
                        type: 'info'
                    });
                    return false
                }
                // console.log(params.id)
                _this.$confirm('该操作会永久删除该字典记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params, _sucess_callback)
                }).catch(() => {});
            },
            detailsave() {
                let _this = this,
                    url = api.dictCrd,
                    params = this.detailFormValue

                params['parent_id'] = this.editTypeID

                if (params['id'] && params['id'] != '') {
                    url = api.dictEdt
                }

                let _sucess_callback = function() {
                    _this.getDetailTableList()
                    _this.handleCloseBindDetailDialogForm()
                }

                _this.handleAxiosFun(url, params, _sucess_callback)
            },
            // 保存
            save() {
                let _this = this,
                    url = api.dictTypeCrd,
                    params = this.formValue

                if (params['id'] && params['id'] != '') {
                    params['type'] = 1
                    url = api.dictTypeEdt
                }

                _this.handleAxiosFun(url, params)
            },
            // axios接口请求
            handleAxiosFun(url, params, _sucess_callback, _fail_callback) {
                let _this = this

                _this.axios.post(url, params).then((res) => {
                    if (res.data.code == 10000) {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'success'
                        });
                        if (_sucess_callback && typeof _sucess_callback === 'function') {
                            _sucess_callback()
                        } else {
                            _this.getTableList()
                            _this.handleCloseBindDialogForm()
                        }
                    } else {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                        if (_fail_callback && typeof _fail_callback === 'function') {
                            _fail_callback()
                        }
                    }
                }).catch(() => {
                    _this.$message({
                        showClose: false,
                        message: '调用失败',
                        type: 'error'
                    });
                })
            }
        }
    }
</script>

<style lang="scss">
    .avue-crud__right {
        position: relative;
    }

    .fast-search {
        position: absolute;
        right: 218px;
    }
</style>
